package cn.itcast.bos.service.impl;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.repository.CourierRepository;
import cn.itcast.bos.service.CourierService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Set;

/**
 * Created by Think on 2017/9/16.
 */
@Service
@Transactional
public class CourierServiceImpl implements CourierService {
    @Autowired
    private CourierRepository courierRepository;

    @Override
    @RequiresPermissions(value = "courier_add")// courier_add表示用户不能访问到该方法,用户的权限是courier:add
    public void save(Courier courier) {
        courierRepository.save(courier);
    }

    public Page<Courier> findPageQuery(Pageable pageable){
        Page<Courier> page = courierRepository.findAll(pageable);
        return page;
    }

    public Page<Courier> findPageQueryCondition(Specification<Courier> specification, Pageable pageable){
        return courierRepository.findAll(specification,pageable);
    }

    @Override
    public void deleteCourierById(String[] idArray) {
        // 调用DAO实现 update修改操作，将deltag 修改为1
        for (String id : idArray) {
            courierRepository.updateDelTag(Integer.valueOf(id));
        }
    }

    @Override
    public void restoreCourierById(String[] idArray) {
        // 调用DAO实现 update修改操作，将deltag 修改为''
        for (String id : idArray) {
            courierRepository.restoreDelTag(Integer.valueOf(id));
        }
    }

    @Override
    public List<Courier> findnoassociation() {
        //中间表的数据为空的条件
        Specification<Courier> spec = new Specification<Courier>() {
            @Override
            public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.isEmpty(root.get("fixedAreas").as(Set.class));//表示courier中的fixedAreas定区属性为空,就是没有关联定区
                return predicate;
            }
        };
        List<Courier> list = courierRepository.findAll(spec);
        return list;
    }

    @Override
    public List<Courier> findAssociationCourier(String fixedAreaId) {
        return courierRepository.findAssociationCourier(fixedAreaId);
    }
}
